from datetime import datetime
from .dao import ExhibitionDAO
from app.utils.logger import logger

class ExhibitionService:
    def __init__(self, db=None):
        self.db = db
        self.exhibition_dao = ExhibitionDAO(db=self.db)

    def get_exhibition_list(self, page=1, page_size=10, filters=None, order_by='id', order='desc', is_industry_mismatch=None):
        """
        获取展会列表
        Args:
            page: 页码
            page_size: 每页数量
            filters: 过滤条件，如 {'chinese_name': '展会名称', 'city': '城市'}
            order_by: 排序字段
            order: 排序方式（asc/desc）
            is_industry_mismatch: 是否筛选行业与AI不一致的展会
        Returns:
            tuple: (展会列表, 总记录数)
        """
        conditions = {}
        if filters:
            for key, value in filters.items():
                if value:
                    if key == 'chinese_name':
                        conditions['(chinese_name LIKE OR english_name LIKE OR english_short_name LIKE)'] = (f'%{value}%', f'%{value}%',f'%{value}%')
                    elif key == 'date_from':
                        conditions['event_date_start >='] = value
                    elif key == 'date_to':
                        conditions['event_date_end <='] = value
                    else:
                        conditions[key] = value
        
        # 单独处理is_industry_mismatch参数
        if is_industry_mismatch == 'true':
            try:
                # 检查数据库中是否存在industry和industry_ai字段
                columns_exist = self.exhibition_dao.check_columns_exist(['industry', 'industry_ai'])
                if columns_exist:
                    # 如果字段存在，添加过滤条件
                    conditions['industry != industry_ai AND industry_ai IS NOT NULL'] = None
            except Exception as e:
                # 如果出现错误，记录日志但不添加此过滤条件
                logger.warning(f"应用industry_mismatch过滤器失败: {str(e)}")
        
        # 获取分页数据和总记录数
        items = self.exhibition_dao.get_exhibition_list(page, page_size, conditions, order_by, order)
        total = self.exhibition_dao.get_total_count(conditions)
        return items, total

    def create_exhibition(self, data):
        """创建展会"""
        data['created_at'] = datetime.now()
        data['updated_at'] = datetime.now()
        return self.exhibition_dao.create(data)

    def update_exhibition(self, exhibition_id, data):
        """
        更新展会信息
        Args:
            exhibition_id: 展会ID
            data: 更新的数据字典
        Returns:
            dict: 更新后的展会信息
        """
        try:
            # 检查展会是否存在
            existing_exhibition = self.exhibition_dao.get_by_id(exhibition_id)
            if not existing_exhibition:
                raise ValueError(f"展会ID {exhibition_id} 不存在")

            # 更新时间戳
            data['updated_at'] = datetime.now()
            
            # 如果修改了展会编号，检查新编号是否已存在
            if ('exhibition_number' in data  and str(data['exhibition_number']).isdigit() and data['exhibition_number'] !=
                    existing_exhibition[
                'exhibition_number']):
                existing = self.exhibition_dao.get_exhibition_by_code(data['exhibition_number'])
                if existing:
                    raise ValueError(f"展会编号 {data['exhibition_number']} 已存在")
            
            # 执行更新操作
            updated_exhibition = self.exhibition_dao.update_exhibition(exhibition_id, data)
            if not updated_exhibition:
                raise ValueError("更新展会信息失败")
                
            return updated_exhibition
            
        except ValueError as e:
            logger.warning(f"更新展会失败: {str(e)}")
            raise
        except Exception as e:
            logger.error(f"更新展会时发生错误: {str(e)}")
            raise ValueError("更新展会信息失败")
            


    def delete_exhibition(self, exhibition_id):
        """删除展会"""
        return self.exhibition_dao.soft_delete_exhibition(exhibition_id)

    def get_exhibition_by_code(self, code):
        """根据编号获取展会"""
        return self.exhibition_dao.get_exhibition_by_code(code)

    def get_exhibition_by_id(self, exhibition_id):
        """
        根据ID获取展会详情
        Args:
            exhibition_id: 展会ID
        Returns:
            dict: 展会信息
        """
        exhibition = self.exhibition_dao.get_by_id(exhibition_id)
        
        if not exhibition:
            return None
            
        # 转换为字典格式
        return exhibition

    def get_exhibition_by_name(self, chinese_name):
        """根据展会中文名称查询展会信息"""
        return self.exhibition_dao.get_exhibition_by_name(chinese_name)

    def get_exhibition_by_name_and_time(self, name, holding_time):
        """根据展会名称和举办时间查询展会"""
        return self.exhibition_dao.get_exhibition_by_name_and_time(name, holding_time)

    def get_total_count(self, filters=None):
        """
        获取符合条件的展会总数
        Args:
            filters: 过滤条件，如 {'chinese_name': '展会名称', 'city': '城市'}
        Returns:
            int: 总记录数
        """
        try:
            conditions = {}
            if filters:
                for key, value in filters.items():
                    if value:
                        conditions[key] = value
            
            return self.exhibition_dao.get_total_count(conditions)
        except Exception as e:
            logger.error(f"获取展会总数失败: {str(e)}")
            return 0

    def get_all_exhibitions(self):
        """获取所有展会数据"""
        try:
            # 通过 DAO 层获取所有展会数据
            exhibitions = self.exhibition_dao.get_all_exhibitions()
            
            # 处理数据
            for exhibition in exhibitions:
                if exhibition.get('exhibition_area'):
                    exhibition['exhibition_area'] = exhibition['exhibition_area']
                    
            return exhibitions
            
        except Exception as e:
            logger.error(f"获取所有展会数据失败: {str(e)}")
            raise ValueError("获取展会数据失败")
